import * as bcryptjs from 'bcryptjs'
import { Injectable } from '@nestjs/common'
import { CreateAuthDto } from './dto/create-auth.dto'
import { UpdateAuthDto } from './dto/update-auth.dto'
import { InjectRepository } from '@nestjs/typeorm/dist/common/typeorm.decorators'
import { AuthEntity } from './entities/auth.entity'
import { Repository } from 'typeorm/repository/Repository'
import { JwtService } from '@nestjs/jwt'
import { BadRequestExceptionFn } from '@/util/exceptions'
// import { RedisService } from '../redis/redis.service';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(AuthEntity)
    private readonly authRepo: Repository<AuthEntity>,
    private readonly JwtService: JwtService,
    // private readonly redisService: RedisService, // 注册redis控制器
  ) {}

  // 注册
  async register(signupData: CreateAuthDto) {
    const findUser = await this.authRepo.findOneBy({
      username: signupData.username,
    })
    if (findUser && findUser.username === signupData.username)
      return '用户已存在'
    // 对密码进行加密处理
    signupData.password = bcryptjs.hashSync(signupData.password, 10)
    await this.authRepo.save(signupData)
    // 尝试将注册成功的用户存入redis中
    // this.redisService.set(signupData.username, signupData.password);
    return '注册成功'
  }

  // 登录
  async login(loginData: CreateAuthDto) {
    const findUser = await this.authRepo.findOneBy({
      username: loginData.username,
    })
    // 没有找到
    if (!findUser) return BadRequestExceptionFn('用户不存在或密码不正确')

    // 找到了对比密码
    const compareRes: boolean = bcryptjs.compareSync(
      loginData.password,
      findUser.password,
    )
    // 密码不正确
    if (!compareRes) return BadRequestExceptionFn('用户不存在或密码不正确')
    const payload = { username: findUser.username }

    return {
      access_token: this.JwtService.sign(payload),
      msg: '登录成功',
    }
  }

  async create(createAuthDto: CreateAuthDto) {
    return await this.authRepo.save(createAuthDto)
  }

  findAll() {
    return `This action returns all auth`
  }

  findOne(id: number) {
    const user = this.authRepo.findOneBy({ id })
    if (!user) return '用户不存在'
    return user
  }

  async update(id: number, updateAuthDto: UpdateAuthDto) {
    return await this.authRepo.update(id, updateAuthDto)
  }

  remove(id: number) {
    return `This action removes a #${id} auth`
  }
}
